<?php 


$opts['hn'] = EW_CONN_HOST;
$opts['un'] = EW_CONN_USER;
$opts['pw'] = EW_CONN_PASS;
$opts['db'] = EW_CONN_DB;
//EW_CONN_PORT


if (getParameter("table")) setParameterInSession("table");
$opts['tb'] =  getParameterFromSession("table");

$tablename=$opts['tb'];


//echo "init ".$tablename." ".getParameter("table");
$realtablename=$tablename;

$tmp=getObjByKey("portal_objects","mappedtoId","name",$tablename);
if ($tmp!="") {
	$tablename=getObjByKey("portal_objects","name","id",$tmp);
	$opts['tb']=$tablename;
}


// Name of field which is the unique key
$opts['key'] = 'id';

$opts['page_name'] = '/butterflyportal/'.basename($_SERVER["SCRIPT_FILENAME"], '.php').".php";

// Type of key field (int/real/string/date etc.)
$opts['key_type'] = 'int';

if ((getParameter("showmaster") && (getParameter("showmaster")!=$realtablename)) || !getParameter("showmaster")) {
// Sorting field(s)
	$defaultsort=preg_split("/\//", getObjByKey("portal_objects","sort","name",$realtablename));
$opts['sort_field'] = array_merge($defaultsort,array("ORDERCMPNT","ID"));

	
}

// Number of records to display on the screen
// Value of -1 lists all records in a table
$opts['inc'] = 15;
$recordperpage=getObjByKey("portal_objects","recordperpage","name",$realtablename);
if ($recordperpage!="") $opts['inc']=$recordperpage;



$tableId=getObjByKey("portal_objects","id","name",$tablename);
$realtableId=getObjByKey("portal_objects","id","name",$realtablename);



// Options you wish to give the users
// A - add,  C - change, P - copy, V - view, D - delete,
// F - filter, I - initial sort suppressed
$options= getObjByKey("portal_objects","operations","name",$realtablename);

if (! canAdd("portal_objects", $tableId)) $options=str_ireplace("A", "", $options);

if (! canEdit("portal_objects", $tableId)) $options=str_ireplace("C", "", $options);

if (! canRemove("portal_objects", $tableId)) $options=str_ireplace("D", "", $options);

//	if (! canAdd("portal_objects", $tableId)) $options=str_ireplace("V", "", $options);


$opts['options'] = $options;


$tablefilter=getObjByKey("portal_objects","filter","name",$realtablename);
if ($tablefilter!="") $tablefilter.=" and ";
$getfilter="";

$detailtable="";


//echo "tab ".$tablefilter;

if (getParameter("filter") || getParameterFromSession("filter"))
{
	if ($tablefilter!="") $getfilter=" and ";
	$getfilter.="ButterflyPortaltable0.".(getParameter("filter")!=null?getParameter("filter"):getParameterFromSession("filter"));
	//echo $getfilter;
	//if ($getfilter!=" and 1") $getfilter="ButterflyPortaltable0.".$getfilter;
	if (getParameter("filter")!=null) {
		setParameterInSession("filter");
		$parameters=preg_split("/&/", getParameter("filter"));
		
		foreach ($parameters as $parameter)
		{
			$parameter=preg_split("/=/", $parameter);
			if (count($parameter)>1)
			setParameter($parameter[0], $parameter[1]);
			//$parameters=preg_split("/=/", $parameter);
		}
		
		
	}
	$detailtable=preg_split("/objectId=/", $getfilter);
	//print_r($detailtable);
	if (count($detailtable)>1) 
		$detailtable="(".getObjByKey("portal_objects","lib_".$LANG,"id",$detailtable[1]).")";
	else $detailtable=null;
	//if ($detailtable=

}

//echo "tab ".$getfilter;

//if ($getfilter=="ButterflyPortaltable0.1") $getfilter="";
$getfilter=preg_replace("/and ButterflyPortaltable0.1/", "", $getfilter);
//set filter paramaters to filter
foreach ($_REQUEST as $param=>$value)
{
	$pos=stripos($param,"filter_");

	if ($pos!==false)
	{
		$param=preg_replace("/filter_/", "", $param);
		if ($pos==0 && $value!=null) $getfilter.="ButterflyPortaltable0.".$param."=".$value." and ";
	}
}
if (endsWith($getfilter,"and ")) $getfilter.=" 1=1 ";

if ((getParameter("showmaster")!=$realtablename))  	$opts['filters'] = $tablefilter."".$getfilter;

else {
	
	 $getfilter="ButterflyPortaltable0.id=".getParameter("masterkey");
	 if (!getParameter("masterkey"))  $getfilter="";
	
	$opts['filters'] = $tablefilter."".$getfilter;
}

$opts['filters']=preg_replace("/and  and/", "and", $opts['filters']);
$opts['filters']=preg_replace("/\( and/", "\(", $opts['filters']);



if (endsWith($opts['filters'],"and  ")) {

	$opts['filters']=substr($opts['filters'], 0,strlen($opts['filters'])-5); 
}

if (endsWith($opts['filters'],"and ")) {

	$opts['filters']=substr($opts['filters'], 0,strlen($opts['filters'])-5);
}
//echo "/".$opts['filters']."/";
//echo $opts['filters']."kjlj".getParameter("filter")."/".getParameterFromSession("filter");
$opts['sort'] = getObjByKey("portal_objects","sort","name",$realtablename)." ";




// Number of lines to display on multiple selection filters
$opts['multiple'] = '4';

// Navigation style: B - buttons (default), T - text links, G - graphic links
// Buttons position: U - up, D - down (default)
$opts['navigation'] = 'DB';

// Display special page elements
$opts['display'] = array(
		'form'  => true,
		'query' => true,
		'sort'  => true,
		'time'  => true,
		'tabs'  => true
);



if (getParameter("showmaster") && (getParameter("showmaster")==$realtablename)) {
	$opts['navigation'] = 'T';
	// Display special page elements
	$opts['display'] = array(
			'form'  => false,
			'query' => false,
			'sort'  => false,
			'time'  => false,
			'tabs'  => false
	);
	
}


//ajaxmode
if (basename($_SERVER["SCRIPT_FILENAME"], '.php')!="index") {
	// Display special page elements
	$opts['display'] = array(
			'form'  => true,
			'query' => false,
			'sort'  => false,
			'time'  => false,
			'tabs'  => false
	);

}



//print_r($opts['display']);

// Set default prefixes for variables
$opts['js']['prefix']               = 'ButterflyPortal_js_';
$opts['dhtml']['prefix']            = 'ButterflyPortal_dhtml_';
$opts['cgi']['prefix']['operation'] = 'ButterflyPortal_op_';
$opts['cgi']['prefix']['sys']       = 'ButterflyPortal_sys_';
$opts['cgi']['prefix']['data']      = 'ButterflyPortal_data_';
//$opts['filters'] = "defaultLang=2";

/* Get the user's default language and use it if possible or you can
 specify particular one you want to use. Refer to official documentation
for list of available languages. */
$opts['language'] = $_SERVER['HTTP_ACCEPT_LANGUAGE'] . '-UTF8';



/* Table-level filter capability. If set, it is included in the WHERE clause
 of any generated SELECT statement in SQL query. This gives you ability to
work only with subset of data from table.

$opts['filters'] = "column1 like '%11%' AND column2<17";
$opts['filters'] = "section_id = 9";
$opts['filters'] = "ButterflyPortaltable0.sessions_count > 200";
*/

/* Field definitions
  
Fields will be displayed left to right on the screen in the order in which they
appear in generated list. Here are some most used field options documented.

['name'] is the title used for column headings, etc.;
['maxlen'] maximum length to display add/edit/search input boxes
['trimlen'] maximum length of string content to display in row listing
['width'] is an optional display width specification for the column
e.g.  ['width'] = '100px';
['mask'] a string that is used by sprintf() to format field output
['sort'] true or false; means the users may sort the display on this column
['strip_tags'] true or false; whether to strip tags from content
['nowrap'] true or false; whether this field should get a NOWRAP
['select'] T - text, N - numeric, D - drop-down, M - multiple selection
['options'] optional parameter to control whether a field is displayed
L - list, F - filter, A - add, C - change, P - copy, D - delete, V - view
Another flags are:
R - indicates that a field is read only
W - indicates that a field is a password field
H - indicates that a field is to be hidden and marked as hidden
['URL'] is used to make a field 'clickable' in the display
e.g.: 'mailto:$value', 'http://$value' or '$page?stuff';
['URLtarget']  HTML target link specification (for example: _blank)
['textarea']['rows'] and/or ['textarea']['cols']
specifies a textarea is to be used to give multi-line input
e.g. ['textarea']['rows'] = 5; ['textarea']['cols'] = 10
['values'] restricts user input to the specified constants,
e.g. ['values'] = array('A','B','C') or ['values'] = range(1,99)
['values']['table'] and ['values']['column'] restricts user input
to the values found in the specified column of another table
['values']['description'] = 'desc_column'
The optional ['values']['description'] field allows the value(s) displayed
to the user to be different to those in the ['values']['column'] field.
This is useful for giving more meaning to column values. Multiple
descriptions fields are also possible. Check documentation for this.
*/






$Security->TablePermission_Loading();
$Security->LoadCurrentUserLevel($tablename);
$Security->TablePermission_Loaded();

if (!$Security->CanList()) {
	$Security->SaveLastUrl();
	//redirect("/?action=login");
}

// Update last accessed time
if ($UserProfile->IsValidUser(session_id())) {
	if (!$Security->IsSysAdmin())
		$UserProfile->SaveProfileToDatabase(CurrentUserName()); // Update last accessed time to user profile
} else {
	echo $Language->Phrase("UserProfileCorrupted");
}




$opts['fdd']=array();

if (getParameter("action")=="refreshtable")
{
	refreshTable($tablename);

}


//if cannot view this table redirecto home
if ($realtableId && !canView("portal_objects", $tableId))
{
	//redirect("/");

	//echo "ok";
	ShowError("You are not able to see this page !");
exit();
}


if ($rs = ew_LoadRecordset("select * from portal_tables_fields where objectId=$tableId order by orderCmpnt ASC"))
{
	$firsttimestamp=true;
	if ($rs->RecordCount()==0) ShowWarning("Refresh this table to retrieve columns from database schema.");
	
	//$object=getObjByKey("portal_objects","objectId");
	
	$arrValidation= array(
			'Date'     => "dateIso",
			'DateTime' => "dateIso",
			'Mail'   => "email",
			'Phone'  => "phone",
			'Numeric'   => "number",
			'Url'     => "url",
			'AlphaNumeric'  => "alphanum"
	
	);
	
	while(! $rs->EOF)
	{
		$field=strtoupper($rs->fields["fieldname"]);
		$fieldlabel=$rs->fields["lib_$LANG"];
		
		//loading default rights
		$options=strtoupper($rs->fields["options_value"]);
		
		
		//overrindign default right by portal rights
		
		if (! canAdd("portal_objects", $tableId)) $options=str_ireplace("A", "", $options);

		if (! canEdit("portal_objects", $tableId)) $options=str_ireplace("C", "", $options);

		if (! canRemove("portal_objects", $tableId)) $options=str_ireplace("D", "", $options);

	//	if (! canAdd("portal_objects", $tableId)) $options=str_ireplace("V", "", $options);
	
	
		
		$maxlen=$rs->fields["maxlen"];
		$default=$rs->fields["default_value"];
		$defaultedit=$rs->fields["edit_default"];
		$select=$rs->fields["select_value"];
		$type=$rs->fields["type"];
		$viewtag=$rs->fields["viewtag"];
		$edittag=$rs->fields["edittag"];
		$uploadpath=$rs->fields["uploadpath"];
		$mandatory=strtolower($rs->fields["mandatory"]);
		$validation=$rs->fields["validation"];
		$editlabel=safeDomName(getObjByKey("portal_object_edit_labels","labelName","id",$rs->fields["editlabelId"]));
		//'Date','DateTime','Mail','Phone','Numeric','Url','AlphaNumeric'
		
		//echo "ok".$validation;
		
	
		
		if ($validation!="")
		$validation=$arrValidation[$validation];
		
		
		$sort=false;
		if ($rs->fields["sort"]=='Y') $sort=true;
		
		$opts['fdd'][$field] = array(
				'name'     => $field,
				'label' => $fieldlabel,
				'select'   => $select,
				'options'  => $options, // auto increment
				'maxlen'   => $maxlen,
				'sort'     => true,
				'type'  => $type,
				'viewtag'  => $viewtag,
				'edittag'  => $edittag,
				'uploadpath'  => $uploadpath,
				'defaultedit'  => $defaultedit,
				'mandatory'  => $mandatory,
				'validation' => $validation,
				'editlabel' => $editlabel
				
		);
		//echo "/".$rs->fields["textarea_rows"]."/";
		if ($rs->fields["textarea_rows"]!=0 && $rs->fields["textarea_cols"]!=0){
		$opts['fdd'][$field]['textarea']['rows'] = $rs->fields["textarea_rows"];
		$opts['fdd'][$field]['textarea']['cols'] = $rs->fields["textarea_cols"];
		}
		
		$opts['backurl']=getObjByKey("portal_objects","backurl","name",$tablename);
		
		if ($rs->fields["values_table"]!=""){
		$opts['fdd'][$field]['values']=array();
		/*$opts['fdd'][$field]['values']['table']=getObjByKey("portal_objects","name","id",$rs->fields["values_table"]);
2		//echo getObjByKey("portal_objects","name","id",$rs->fields["values_table"])." ".getObjByKey("portal_tables_fields","name","id",$rs->fields["values_column"])." ".getObjByKey("portal_tables_fields","name","id",$rs->fields["values_description"]);
		$opts['fdd'][$field]['values']['column']=getObjByKey("portal_tables_fields","fieldname","id",$rs->fields["values_column"]);
		$opts['fdd'][$field]['values']['description']=getObjByKey("portal_tables_fields","fieldname","id",$rs->fields["values_description"]);*/
		//echo $rs->fields["values_table"];
		$opts['fdd'][$field]['values']['table']=$rs->fields["values_table"];
		$opts['fdd'][$field]['values']['column']=$rs->fields["values_column"];
		
		if ($rs->fields["values_key"]!="") $opts['fdd'][$field]['values']['key']=$rs->fields["values_key"];
		else $opts['fdd'][$field]['values']['key']=$rs->fields["values_column"];
		
		
		
		$opts['fdd'][$field]['values']['sub_table']=$rs->fields["sub_values_table"];
		$opts['fdd'][$field]['values']['sub_column']=$rs->fields["sub_values_column"];
		
		
		//$opts['fdd'][$field]['values']['description']=$rs->fields["values_description"];
		if (strpos($rs->fields["values_description"],",")!==false) {
			$opts['fdd'][$field]['values']['description']['columns']=preg_split("/,/", $rs->fields["values_description"]);
		}
		else
			
			$opts['fdd'][$field]['values']['description']=$rs->fields["values_description"];
		
		
		
	
		
		
		
		if (strpos($rs->fields["sub_values_description"],",")!==false) {
			$opts['fdd'][$field]['values']['sub_description']['columns']=preg_split("/,/", $rs->fields["sub_values_description"]);
		}
		else
				
				$opts['fdd'][$field]['values']['sub_description']=$rs->fields["sub_values_description"];
		
		
		
			//	$opts['fdd'][$field]['values']['filters']=$rs->fields["values_filters"];
		$opts['fdd'][$field]['values']['filters']=$rs->fields["values_filters"];
}
		
		
	
		
		
		//$debug=1;
		$data=array();
			
		$data["portalId"]=$portalId;
		$data["lang"]=$lang;
		$data["LANG"]=$LANG;
		$data["lt"]=$lt;
		$data["CURRENTDATETIME"]=(new DateTime('NOW'))->format("Y-m-d H:i:s");
		
		
		foreach ($_REQUEST as $param=>$value)
		{
			 
			$data[$param]=$value;
		}
		
		// echo $qry;
		
		if ($default!=""){
			$default=TemplateWithData($default,$data);
		
		}
		$opts['fdd'][$field]["default"]=$default;
		

		$rs->MoveNext();
	}
}

//&& basename($_SERVER["SCRIPT_FILENAME"], '.php')=="index"
if ($tablename!="" ){
	
	$table_title=getObjByKey("portal_objects","lib_".$LANG,"name",$realtablename);
?>
<span class="phpmaker title" style="white-space: nowrap;"><img id="table_title_img" width='32' src='images/menu/<?=$realtablename?>.png'>
 <span id="table_title"><?=$table_title ?> <?=$detailtable?></span><br clear="all"/></span>
 
<?php if (getParameter("showmaster")!=$realtablename) { ?>
 <div class="edit_table">
 <a id="searchButton"><img width="32" src="./images/menu/search.png" tilte="Search"></a>
 <?php if (isPortalSuperAdmin()) {?>
 <a href="?table=portal_objects&ButterflyPortal_sys_fl=0&ButterflyPortal_sys_fm=0&ButterflyPortal_sys_operation=ButterflyPortal_op_Change&ButterflyPortal_sys_rec=<?=$realtableId?>"><img width="32" src="./images/menu/portal_objects.png" title="Edit Table Preferences"/></a>
 <a href="?table=portal_credentials&filter=objectId=<?=$tableId ?>&objectName=<?=getObjByKey("portal_objects","id","name","portal_objects")?>"><img width="32" src="./images/menu/portal_userlevelpermissions.png" title="Acces Rights"/></a>
 <a href="?table=portal_tables_fields&filter=objectId=<?=$tableId?>"><img width="32" src="./images/menu/portal_tables_fields.png" title="Edit Table Fields"/></a>
 <a href="?table=portal_masterdetail&filter=masterId=<?=$tableId?>"><img width="32" src="./images/menu/portal_masterdetail.png" title="Edit Master/Details"/></a>
 <a href="?table=<?=$tablename?>&filter=<?=getParameter("filter")?>&action=refreshtable"><img width="32" src="./images/icons/refresh.png" title="Refresh Table"/></a>

 <?php 
}
 $folder=preg_split("/_/", $realtablename)[0];
 $file="system/".$folder."/".$realtablename."_list_option_top.php";
 if (file_exists($file)) {
 	include $file;

 }
 
 
 $masterdetailquery="SELECT portal_objects.`name`,portal_masterdetail.foreignkey,portal_masterdetail.mode,portal_masterdetail.fkvalue FROM portal_masterdetail INNER JOIN portal_objects ON portal_masterdetail.slaveId = portal_objects.id WHERE enabled='Y' and masterId=$tableId";

 //echo $masterdetailquery;
 $rs=ew_LoadRecordset($masterdetailquery);
 while($rs && !$rs->EOF){
 
 	$detailtable=$rs->fields["name"];
 	$foreignKey=$rs->fields["foreignkey"];
 	$fkvalue=@preg_replace('/\#([a-zA-Z0-9_]+)\#/e',"$$1", $rs->fields["fkvalue"]);
 	$mode=$rs->fields["mode"];
 	if ($mode=="Normal"){
 	?>
 						
 						<a id="master_<?=$detailtable?>" title="<?=getObjByKey("portal_objects","lib_".$LANG,"name",$detailtable)?>" onclick="javascript:loadmaster('?table=<?=$detailtable?>&showmaster=<?=$realtablename?>&filter=<?=$foreignKey?>=####&masterkey=####')">
 						<img width="32" height="32" border="0" title="" src="images/menu/<?=$detailtable?>.png"></a>
 							<?php
 							}elseif ($mode=="Iframe"){

$filter=getParameter("filter");


?>
 						
 						<a id="master_<?=$detailtable?>" title="<?=getObjByKey("portal_objects","lib_".$LANG,"name",$detailtable)?>" onclick="javascript:iframe_<?=$detailtable?>();">
 						<img width="32" height="32" border="0" title="" src="images/menu/<?=$detailtable?>.png"></a>
 						
 		<div id="<?=$detailtable?>_iframe_div" title="Master Details"  style="display: none" class="portal_iframe" >
<iframe frameborder="0" id="<?=$detailtable?>_iframe" src="" width="100%" style="border-width: 0px;" height="100%"></iframe>

</div>				
 						
 	<script type="text/javascript">
function iframe_<?=$detailtable?>(){

	id=$("input[name='ButterflyPortal_sys_rec']:checked").val();

	<?php if ($fkvalue!="") echo 'id="'.$fkvalue.'";'; ?>
	
	url="iframe.php?table=<?=$detailtable?>&filter=<?=$foreignKey?>="+id;

$("#<?=$detailtable?>_iframe").attr('src',url); 


			$("#<?=$detailtable?>_iframe_div").dialog({
				autoOpen: true,
				height: 500,
				width: 1000,
				modal: true,
				zIndex: 3999,
				buttons: {
					
					Close: function() {
						$( this ).dialog( "close" );
					}
				}


				});


	
}

</script>					
 						
 							<?php
 							}
 							
 							$rs->MoveNext(); 	
 							}	
 		
 ?>
  </div>
   <?php } ?>
<script type="text/javascript">

$("#searchButton").click(function() {
	$("#ButterflyPortal_sys_sw").click();
});


 
</script>


<script type="text/javascript">
function ajaxadd()
		{



		$.get("/ajax.php?table=<?=$tablename?>&filter=<?=getParameter("filter")?>",
		{app: "system",
		operation:"ajaxadd"},
		   function(data){

			$("#result").html(data);
				$("#result").dialog({
					autoOpen: true,
					height: 300,
					width: 800,
					modal: true,
					zIndex: 3999,
					buttons: {
						"Save": function() {

                            bootbox.alert("Added !");
						},
						Cancel: function() {
							$( this ).dialog( "close" );
						}
					}


					});


		   });



			}

</script>	

<!-- 
<div id="result" title="Add" ></div>

<a href="#" onclick="ajaxadd()">Ajax Add</a> -->
 <?php
}

?>